package com.alogic.remote.httpclient.filter;

import com.alogic.remote.httpclient.HttpCientFilter;
import com.alogic.remote.httpclient.HttpClientRequest;
import com.alogic.remote.httpclient.HttpClientResponse;
import com.alogic.sda.SDAFactory;
import com.alogic.sda.SecretDataArea;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;

/**
 * Http Basic认证
 *
 * @since 1.6.12.54 [20191212]
 */
public class HttpBasicAuth extends HttpCientFilter.Abstract{
    protected String sdaId = "";
    protected String authString;
    protected boolean isRaw = true;

    @Override
    public void onRequest(HttpClientRequest request) {
        SecretDataArea sda = null;
        if (StringUtils.isNotEmpty(sdaId)){
            //从sda中装入信息
            try {
                sda = SDAFactory.getDefault().load(sdaId, true);
            }catch (Exception ex){
                LOG.error("Can not find sda : " + sdaId);
                LOG.error(ExceptionUtils.getStackTrace(ex));
            }
        }

        if (sda != null){
            String authString = sda.getField("auth", "");
            boolean raw = sda.getField("auth.raw",true);
            onRequest(request,authString,raw);
        }else{
            onRequest(request,authString,isRaw);
        }
    }

    protected void onRequest(HttpClientRequest req,String authString,boolean raw){
        if (StringUtils.isNotEmpty(authString)) {
            if (isRaw) {
                req.setHeader("Authorization", String.format("Basic %s", Base64.encodeBase64String(authString.getBytes())));
            }else{
                req.setHeader("Authorization", String.format("Basic %s", authString));
            }
        }else{
            LOG.warn("AuthString is null,ignored");
        }
    }

    @Override
    public void onResponse(HttpClientResponse response) {

    }

    @Override
    public void configure(Properties p) {
        super.configure(p);
        authString = PropertiesConstants.getRaw(p,"auth",authString);
        isRaw = PropertiesConstants.getBoolean(p,"auth.raw",isRaw);
        sdaId = PropertiesConstants.getString(p,"sda",sdaId);
    }
}
